<?php

namespace Contract;

use C\L\AdmController;
use C\R\Contract as ContractResource;

class ContractController extends AdmController
{
    public function indexAction()
    {
        $currentPage = $this->request->getQuery('page', 'int', 1);
        $perPage     = $this->request->getQuery('per_page', 'int', 20);

        $contracts = $this->s_contract->paginate($currentPage, $perPage);

        return $this->success($contracts);
    }

    public function viewAction()
    {
        $id = $this->request->getQuery('id', 'string');

        $contract = $this->s_contract->view($id);

        if (!$contract) {
            return $this->error('查找合同失败');
        }

        $resource = new ContractResource($contract);

        return $this->success($resource->toArray());
    }

    public function createAction()
    {
        $params = $this->getParams();

        $contract = $this->s_contract->store($params);

        if (!$contract) {
            return $this->error('添加合同失败');
        }

        $resource = new ContractResource($contract);

        return $this->success($resource->toArray());
    }

    public function updateAction()
    {
        $id = $this->request->getPost('id', 'string');

        $params = $this->getParams();

        $contract = $this->s_contract->newUpdate($id, $params);

        if (!$contract) {
            return $this->error('更新合同失败');
        }

        $resource = new ContractResource($contract);

        return $this->success($resource->toArray());
    }

    public function deleteAction()
    {
        $id = $this->request->getPost('id', 'string');

        return $this->s_contract->delete($id)
        ? $this->success()
        : $this->error('删除合同失败');
    }

    private function getParams()
    {
        return [
        'name'    => $this->request->getPost('name', 'string'),
        'content' => $this->request->getPost('content'),

        'a_name'  => $this->request->getPost('a_name', 'string'),
        'a_stamp' => $this->request->getPost('a_stamp', 'string'),

        'b_name'  => $this->request->getPost('b_name', 'string'),
        'b_stamp' => $this->request->getPost('b_stamp', 'string'),

        'c_name'  => $this->request->getPost('c_name', 'string'),
        'c_stamp' => $this->request->getPost('c_stamp', 'string'),
        ];
    }
}
